/*
 * Copyright 2013 Nikolay Todorov
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jobinsight.util;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.util.Vector;
import java.util.zip.ZipInputStream;

import javax.swing.JFileChooser;

/**
 * Selects a file with FileChooser and reads and deserialize the data. 
 * 
 * @author todorov
 *
 */
public class ObjReader {
	private static final String LAST_FILE = "LAST_FILE";
	WorkingSettings workingSettings = new WorkingSettings(this.getClass());
	File lastFile = null;
	
	public Object getObject(){
		Object readedObject = null;
		lastFile = selectFile();
		if(lastFile!=null){
			try{
				System.out.println("Try to read "+lastFile.getName()+" as zip ...");
				readedObject = readZippedObject(lastFile.getCanonicalPath());
			} catch (Throwable e) {
				System.out.println(lastFile.getName()+" is obviously not a zip file!");
			}
			
			try{
				if( readedObject==null ){
					readedObject = readMultipleObjects(lastFile.getCanonicalPath());
				}
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		finish();
		return readedObject;
	}
	
	Object readMultipleObjects(String fileName){
		Vector wrappingObj = new Vector();
		try {
			ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(fileName)));
			
			Object obj = null;
			while((obj = ois.readObject()) !=null){
				wrappingObj.add(obj);
			}
			
			ois.close();
		} catch(Throwable e) {
			
		}
		
		if(wrappingObj.size()==1)
			return wrappingObj.firstElement();
		
		return wrappingObj.size()>0?wrappingObj:null;
	}
	
    Object readZippedObject(String fileName) {
        try {
        	ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(fileName)));
            try {
                zis.getNextEntry();
                return readObject(zis);
            } finally { zis.close(); }
        } catch(Exception e) {
            System.err.println(e);
        }
        return null;
    }
    

    Object readObject(InputStream bis) throws Exception {
        ObjectInputStream ois = new ObjectInputStream(bis);
        try {
            return ois.readObject();
        } finally { ois.close(); }
    }
    
	public File getFile(){
		return lastFile;
	}

	
	File selectFile(){
		File result = null;
		JFileChooser fileChooser = createFileChooser("Open serialized objects", "OK");

		int returnVal = fileChooser.showOpenDialog(null);
		if (returnVal == JFileChooser.APPROVE_OPTION) {
			result = fileChooser.getSelectedFile();
			workingSettings.setFile(LAST_FILE, result);
		}
		return result;
	}
	
	void finish(){
		workingSettings.save();
	}

	private JFileChooser createFileChooser( String dialogTitle, String approveButtonText){
		JFileChooser fileChooser = new JFileChooser();
		fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		fileChooser.setDialogType(JFileChooser.OPEN_DIALOG);
		fileChooser.setDialogTitle(dialogTitle);
	    fileChooser.setApproveButtonText(approveButtonText);
	    fileChooser.setCurrentDirectory(workingSettings.getFile(LAST_FILE));
	    return fileChooser;
	}

}


